/*
 * @lc app=leetcode.cn id=202 lang=cpp
 *
 * [202] 快乐数
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

// @lc code=start
class Solution {
public:
    bool isHappy(int n) {
        bool result = false;
        set<int> visited;       // 记录已经出现过的数字
        int number = n;

        while (visited.count(number) == 0) {
            // 如果得到1，则是快乐数，直接返回
            if (number == 1) {
                result = true;
                break;
            }
            
            // 记录该数字
            visited.insert(number);

            // 替换该数字为每位的平方和
            int tmp = 0;
            while (number > 0) {
                int remainder = number % 10;
                number = number / 10;
                tmp = tmp + remainder * remainder;
            }
            number = tmp;
        }
        
        return result;
    }
};
// @lc code=end

